#!/bin/bash

# 默认日志文件路径
LOG_FILE="install.log"

# 默认配置文件路径
CONFIG_FILE="config.cfg"

# 帮助信息
function help_info {
  echo "本工具根据配置文件内容初始化安装部署天固彩石智算平台V3.1。"
  echo "在使用前先根据待部署环境信息修改配置文件。"
  echo "注意：本工具只进行平台的安装部署，具体的配置任务请根据使用手册自行配置。"

  echo "Usage: $0 [-h] [-c <config_file>]"
  echo "  -h  显示帮助信息"
  echo "  -c  指定配置文件路径，如不指定，缺省采用本地./config.cfg"
}

# 读取配置文件
function read_config {
  if [[ -f "$1" ]]; then
    source "$1"
  else
    echo "配置文件不存在: $1" >&2
    exit 1
  fi
}

# 处理参数
while getopts ":hc:" opt; do
  case $opt in
    h)
      help_info
      exit 0
      ;;
    c)
      CONFIG_FILE="$OPTARG"
      ;;
    \?)
      echo "无效选项: -$OPTARG" >&2
      help_info
      exit 1
      ;;
  esac
done

# 读取配置文件
read_config "$CONFIG_FILE"

# 将所有输出重定向到日志文件，并在shell中打印
exec > >(tee -a "$LOG_FILE") 2>&1

if [ -z "$masterNodes" ]; then
  echo "masterNodes不能为空"
  exit 1
fi


echo "start to install k8s and helm"
# 当部署为Allinone模式时，可不配置defaultVIP
if [ -z "$defaultVIP" ]; then
  defaultVIP_pam=""
else
  defaultVIP_pam="-e defaultVIP=$defaultVIP"
fi

if [ -z "$workerNodes" ]; then
  # install k8s helm
  echo $defaultVIP_pam
  echo $massterNodes

  sealos run $defaultVIP_pam -e BIN_DIR="/usr/local/bin" labring/kubernetes:v1.25.16 labring/helm:v3.12.3 --masters $masterNodes  --passwd $serverPasswd
  sleep 30
else
  # install k8s helm
  echo $defaultVIP_pam
  echo $masterNodes
  echo $workerNodes
  sealos run $defaultVIP_pam -e BIN_DIR="/usr/local/bin" labring/kubernetes:v1.25.16 labring/helm:v3.12.3 --masters $masterNodes --nodes $workerNodes --passwd $serverPasswd
  sleep 30
fi

echo "start to config ipv4_ip_local_port_range to 32768 60999"
deploy_update_sysctl() {
  echo "sed -i 's/net.ipv4.ip_local_port_range=1024 65535/net.ipv4.ip_local_port_range=32768 60999/' /etc/sysctl.conf && sysctl -p" > update_sysctl.sh
  chmod +x update_sysctl.sh
  sealos scp ./update_sysctl.sh /tmp/update_sysctl.sh
  sealos exec "/tmp/update_sysctl.sh && rm -rf /tmp/update_sysctl.sh"
  rm -rf ./update_sysctl.sh
  sleep 2
}

deploy_update_sysctl


echo "start to install calico"
sealos run labring/calico:3.24.6 -e HELM_OPTS="--set installation.calicoNetwork.nodeAddressAutodetectionV4.interface=null --set installation.calicoNetwork.nodeAddressAutodetectionV4.kubernetes=NodeInternalIP" 

echo "start to install calicoctl"
sealos run labring/calicoctl:v3.24.6

#sleep 3min
sleep 180

# 无限循环直到节点数量达到6个
while true; do
    # 获取Ready状态的节点数量
    ready_nodes_count=$(kubectl get nodes | grep NotReady | wc -l)
    # 判断NotReady节点数量是否大于0
    if [ $ready_nodes_count -gt 0 ]; then
        echo "当前NotReady状态的节点数量大于0，等待1分钟后重试。"
        sleep 60
    else
        echo "当前NotReady状态的节点数量为0，继续执行。"
        # 在这里继续执行后续的命令
        # ...
        break # 跳出循环
    fi
done


if [ "$taintMasterNodes" == "1" ]; then
  echo "start to taint master nodes"
  kubectl taint nodes --all node-role.kubernetes.io/control-plane-
  sleep 5
fi

if [ "$needLoadBalancer" == "1" ]; then
  echo "start to  install LoadBalaner kube-vip"

  if [ -z "$lbInterface" ] || [ -z "$lbIPRange" ]; then
    echo "必须指定负载均衡网卡和负载均衡IP地址范围"
    exit 1
  fi

  sealos run labring/kube-vip:v0.5.10 -e  kube_vip_interface=$lbInterface -e kube_vip_address=$defaultVIP -e controller_enabled=true -e range_global=$lbIPRange
  sleep 60
fi

echo "start to install cert-manager"
sealos run labring/cert-manager:v1.12.1
sleep 120

echo "start to install ingress-nignx"
sealos run labring/ingress-nginx:v1.6.4 -e HELM_OPTS="--set controller.hostNetwork=true --set controller.kind=DaemonSet"
sleep 120

if [ "$needRancher" == "1" ]; then
  echo "start to install rancher"
  if [ -z "$rancherHostname" ]; then
    rancherHostname = "rancher.abc.com.cn"
  fi
  sealos run labring/rancher:v2.7.5 --env hostname=$rancherHostname
  sleep 180
  
  while true; do
    kubectl get deployments -n cattle-system | grep -E '([0-9]+)/\1'
    if [ "$?" == "0" ]; then
      echo "rancher 已部署完成"
      break
    else
      sleep 60
    fi
  done
fi


if [ "$needOpenebsHostpath" == "1" ]; then
  echo "start to install openebs-localpv-hostpath"
  sealos run labring/openebs:v3.7.0
  sleep 10
fi

if [ "$needLonghorn" == "1" ]; then
  echo "start to install Longhorn storage"
  sealos run labring/longhorn:v1.4.3
  sleep 180
fi

if [ "$needMinio" == "1" ]; then
  echo "start to install minio object storage"
  sealos run labring/minio-operator:v5.0.12
  sleep 20
fi

## Install MultiNetwork support


if [ "$needMultiNetwork" == "1" ]; then
  if [ "$multiNetworkIPAM" == "whereabouts" ]; then
    echo "start to install Multi Networks plugin multus-cni"
    sealos run labring/multus-cni:v4.0.2
    sleep 20

    echo "start to install IPAM plugin whereabouts"
    sealos run labring/whereabouts:v0.6.3
    sleep 20
    
    if [ "$needRdmaShared" == "1" ]; then
      echo "start to install k8s-rdma-shared-dev-plugin"
      sealos run labring/k8s-rdma-shared-dev-plugin:v1.5.0
      sleep 20
    fi
  elif [ "$multiNetworkIPAM" == "spiderpool" ]; then
    if [ "$needRdmaShared" == "1" ]; then
      echo "start to install spiderpool and RDMA shared device plugin"
      sealos run labring/spiderpool:v0.9.6
      sleep 20
    else
      echo "start to install spiderpool without RDMA shared device plugin"
      sealos run labring/spiderpool:v0.9.6 -e HELM_OPTS="--set rdma.rdmaSharedDevicePlugin.install=false"
      sleep 20
    fi
  fi
fi


if [ "$needMonitoring" == "1" ]; then
  echo "start to install rancher-monitor app"
  if [ "$needRancher" == "1" ]; then
    sealos run labring/rancher-monitor:v102.0.1-up40.1.2
    sleep 20
  else
    echo "没有安装Rancher，请先安装Rancher"
    exit 1
  fi
fi

if [ "$needJuicefsClient" == "1" ]; then
  echo "start to install Juicefs Client and Juicefs-csi-driver"
  sealos run labring/juicefs:v1.1.2 labring/juicefs-csi-driver:v0.19.8
  sleep 30
fi

if [ "$needJuicefsCluster" == "1" ]; then
  echo "start to install MetaData cluster: Postgresql-HA cluster"

  if [ "$needLonghorn" == "1" ] || [ "$needOpenebsHostpath" == "1" ]; then
    if [ -z "$postgreDBName" ]; then
      postgreDBName="juicefs"
    fi

    if [ -z "$postgresqlSC" ]; then
      postgresqlSC_set=""
    else
      postgresqlSC_set="--set global.storageClass=${postgresqlSC}"
    fi

    sealos run labring/bitnami-postgresql-ha:v15.4.0 -e HELM_OPTS="--set service.type=NodePort $postgresqlSC_set --set global.postgresql.database=${postgreDBName}"
    sleep 30

  else
    echo "要部署Postgresql HA集群，需要先部署持久化存储组件"
    exit 1
  fi

  if [ "$needMinio" == "1" ]; then
    echo "已部署数据集群 Minio"
  else
    echo "请先部署数据集群 Minio"
    exit 1
  fi
fi


if [ "$needNvidiaGpu" == "1" ]; then
  echo "start to deploy nvidia-gpu-dev-pulgin"

  # 检查 nvidiaGpuReplicas 是否定义
  if [ -z "$nvidiaGpuReplicas" ]; then
      # 未定义变量，设置默认值
      echo "nvidiaGpuReplicas not define, set to 1"
      nvidiaGpuReplicas=1
  else
      # 检查是否为正整数
      if ! [[ "$nvidiaGpuReplicas" =~ ^[1-9][0-9]*$ ]]; then
          # 不是正整数，设置默认值
          echo "nvidiaGpuReplicas=$nvidiaGpuReplicas, not invalid value, set to 1"
          nvidiaGpuReplicas=1
      fi
  fi
  
  sealos run labring/nvidia-k8s-device-plugin:v0.15.0 -e sharenum=$nvidiaGpuReplicas
  sleep 40
fi

echo "安装完成"
